<template>
	<view class="index">
		<view v-if="tabberPageLoadFlagShow(0)" :style="{display: currentIndex === 0 ? '' : 'none'}">
			<scroll-view class="custom-tabbar-page" :style="{height:webviewHeight + 'px'}" scroll-y enable-back-to-top
				@scrolltolower="tabbarPageScrollLower">
				<pages-home ref="home" :config="scrollConfig"></pages-home>
			</scroll-view>
		</view>

		<view v-if="tabberPageLoadFlagShow(1)" :style="{display: currentIndex === 1 ? '' : 'none'}">
			<scroll-view class="custom-tabbar-page" :style="{height:webviewHeight + 'px'}" scroll-y enable-back-to-top
				@scrolltolower="tabbarPageScrollLower">
				<Center ref="center"></Center>
			</scroll-view>
		</view>

		<view v-if="tabberPageLoadFlagShow(3)" :style="{display: currentIndex === 3 ? '' : 'none'}">
			<scroll-view class="custom-tabbar-page" :style="{height:webviewHeight + 'px'}" scroll-y enable-back-to-top
				@scrolltolower="tabbarPageScrollLower">
				<Mine ref="mine"></Mine>
			</scroll-view>
		</view>


		<view class="tabbar">
			<up-tabbar :value="currentIndex" :fixed="false" :safeAreaInsetBottom="safeAreaInsetBottom"
				activeColor="#51d0d0" :midButton="true" inactiveColor="#707070" @change="switchTabbar">
				<up-tabbar-item v-for="(item,index) in tabbarList" :text="item.title" :name="item.id"
					:badge="item.badge" :icon="currentIndex==item.id ? item.activeIcon : item.inactiveIcon">
				</up-tabbar-item>
			</up-tabbar>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onMounted, ref, reactive, computed } from 'vue';

	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();

	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();

	import pagesHome from '../home/home';
	import Center from '@/st_pages/center/center';
	import Mine from '@/st_pages/mine/mine';

	let safeAreaInsetBottom = ref(true);

	// #ifdef MP-WEIXIN
	safeAreaInsetBottom.value = false;
	// #endif

	let currentIndex = ref(0);

	let tabberPageLoadFlag = ref<any>([])

	// 定义Tabbar菜单项的类型
	interface TabbarItem {
		title : string;
		activeIcon : string;
		inactiveIcon : string;
		id : number;
		badge ?: string; // 可选属性
	}
	const tabbarList = computed<TabbarItem[]>(() => {
		const baseItems : TabbarItem[] = [
			{
				title: '首页',
				activeIcon: 'home-fill',
				inactiveIcon: 'home',
				id: 0,
				badge: ''
			},
			{
				title: '模块',
				activeIcon: 'grid-fill',
				inactiveIcon: 'grid',
				id: 1,
				badge: ''
			},
			{
				title: '消息',
				activeIcon: 'chat-fill',
				inactiveIcon: 'chat',
				id: 2,
				// 假设msgNum是从store中获取的，这里根据实际情况调整
				badge: mainStore.systemConfig.msgConfig.msgNum.toString()
			},
			{
				title: '我的',
				activeIcon: 'account-fill',
				inactiveIcon: 'account',
				id: 3,
				badge: ''
			}
		];

		// 从store中获取数据，这里假设UserInfo的类型已在store中定义
		// const dataValue = userStore.UserInfo.Business;

		// // 判断是否显示Ai菜单
		// const openAi = [1030, 10103, 9051].includes(dataValue);

		// if (openAi) {
		// 	const aiItem : TabbarItem = {
		// 		title: 'Ai',
		// 		activeIcon: '/static/tabbar-icons/ai.png',
		// 		inactiveIcon: '/static/tabbar-icons/ai-fill.png',
		// 		id: 4
		// 	};

		// 	// 插入Ai菜单到指定位置
		// 	return [...baseItems.slice(0, 2), aiItem, ...baseItems.slice(2)];
		// }

		return baseItems;
	});

	function switchTabbar(indexID : number) {
		const handleNavigation = (url : any, shouldReload = false) => {
			if (shouldReload) {
				uni.$emit('msgReload', {
					status: 'reload'
				});
			}
			uni.navigateTo({
				url
			});
		};

		switch (indexID) {
			case 4: {
				// 处理AI模块逻辑
				permissionStore.activeModule = null;
				// permissionStore.activeModuleID = null;
				// uni.removeStorageSync('ActiveModule');
				handleNavigation('/pages/Ai/Ai');
				break;
			}

			case 2: {
				// 处理消息模块逻辑
				uni.setStorageSync('openMsgDate', JSON.stringify(new Date()));

				// 处理消息按钮隐藏逻辑
				const msgConfig = mainStore.systemConfig.msgConfig;
				if (msgConfig.msgBtnIsHide && msgConfig.activeCtx) {
					(msgConfig.activeCtx as { hide : () => void }).hide();
				}

				handleNavigation('/pages/Message/Message?nav=1', true);
				break;
			}

			default: {
				// 默认tab切换逻辑
				_switchTabbarPage(indexID);
				break;
			}
		}
	}

	function _switchTabbarPage(indexID : number) {
		// 查找目标标签页配置
		const targetPage = tabberPageLoadFlag.value.find((item : any) => item.id === indexID);

		// 无效标签页直接返回
		if (!targetPage) return;

		// 处理未初始化状态
		if (targetPage.type === undefined) return;

		// 需要激活时执行状态更新
		if (!targetPage.type) {
			updateTabLoadStatus(indexID);
		}

		// 更新当前激活索引
		currentIndex.value = indexID;
	};

	// 优化后的状态更新方法（移除冗余参数返回）
	function updateTabLoadStatus(id : number) {
		const index = tabberPageLoadFlag.value.findIndex((item : any) => item.id === id);
		if (index !== -1) {

			tabberPageLoadFlag.value[index] = {
				...tabberPageLoadFlag.value[index],
				type: true
			}
		}
	}


	function tabberPageLoadFlagShow(id : number) {
		let findData = tabberPageLoadFlag.value.find((item : any) => item.id == id);
		return findData ? findData['type'] : false;
	}

	function tabbarPageScrollLower() {

	}


	let scrollConfig = reactive<any>({
		scrollHeight: 500,
		tabbarHeight: 50
	});

	let webviewHeight = ref(0)
	// 获取内容高度
	const getContentHeight = () => {
		const windowHeight = uni.$utils.getWindowInfo().windowHeight;
		uni.$utils.$uGetRect('.tabbar').then((res : any) => {
			console.log(res);

			console.log(mainStore.systemConfig.sysDeviceInfo.safeAreaInsets.bottom);
			uni.setStorageSync('safeareaBottom', mainStore.systemConfig.sysDeviceInfo.safeAreaInsets.bottom)
			const heightInfo = windowHeight - res.height - (mainStore.systemConfig.sysDeviceInfo.safeAreaInsets.bottom / 2);
			webviewHeight.value = heightInfo;

			console.log(webviewHeight.value);

			Object.assign(scrollConfig, {
				scrollHeight: heightInfo,
				tabbarHeight: res.height
			})
		});
	};
	onLoad((option : any) => {
		const indexID = Number(option.index) || 0; // 这里修改为ID
		tabberPageLoadFlag.value = tabbarList.value.map((item, tabbar_index) => {
			return {
				id: item.id,
				type: indexID === item.id
			}
		});
		switchTabbar(indexID)
	});


	onMounted(() => {
		getContentHeight();
	});
</script>

<style lang="scss" scoped>
	.index {
		overflow: hidden;
		height: 100vh;
	}



	// .custom-tabbar-page {
	// height: calc(100vh - (50px + env(safe-area-inset-bottom) / 2));
	// }


	::v-deep .middle-item .u-tabbar-item__icon {
		background: red;
		bottom: 20rpx;

		// border-radius: 20rpx;
		.u-icon--right {

			background-color: yellow;
			transform: scale(2);
			border-radius: 20rpx;
		}
	}
</style>